package com.byjh.common.utils.aliyun;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.byjh.common.config.OssConfig;
import com.byjh.common.core.domain.FileObject;
import com.byjh.common.utils.file.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class OssUtil {

    private final OSS ossClient;

    private final OssConfig ossConfig;

    public OssUtil(OSS ossClient, OssConfig ossConfig) {
        this.ossClient = ossClient;
        this.ossConfig = ossConfig;
    }


    public FileObject uploadFile(MultipartFile file) throws IOException {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") +
                getFileExtension(originalFilename);

        // 创建上传文件的元信息
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(file.getContentType());
        metadata.setContentLength(file.getSize());

        // 上传文件
        PutObjectResult result = ossClient.putObject(
                ossConfig.getBucketName(),
                fileName,
                file.getInputStream(),
                metadata
        );

        // 生成文件访问URL
        String fileUrl = String.format("https://%s.%s/%s",
                ossConfig.getBucketName(),
                ossConfig.getEndpoint(),
                fileName);

        return new FileObject()
                .setFileName(fileName)
                .setOriginalFilename(file.getOriginalFilename())
                .setUrl(fileUrl)
                .setFileSize(FileUtils.getFileSize((file.getSize())))
                .setSuffix(FileUtils.getFileSuffix(fileName))
                .setContentType(file.getContentType());
    }


    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") == -1) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }

}
